
function ApplicationModel(stompClient) {
    var self = this;

    self.username = ko.observable();
    self.asset = ko.observable(new AssetModel());
    self.trade = ko.observable(new TradeModel(stompClient));
    self.open = ko.observable(new OpenTrade());
    
    self.connect = function() {
        stompClient.connect({}, function(frame) {

            console.log('Connected ' + frame);
            self.username(frame.headers['user-name']);
            
             stompClient.subscribe("/app/positions", function(message){ 
                self.asset().loadPositions(JSON.parse(message.body));
                self.asset().putTradeObj(self.trade(), self.open());
                self.asset().setDefault(JSON.parse(message.body));
            });
            stompClient.subscribe("/topic/asset.all", function(message) {
                self.asset().loadAssets(JSON.parse(message.body));
            });
            stompClient.subscribe("/user/queue/updates", function(message) {
               self.open().showTrade(JSON.parse(message.body));
            });
            stompClient.subscribe("/user/queue/return", function(message) {
               self.open().tradeReturn(JSON.parse(message.body));
            });

        }, function(error) {
            console.log("STOMP protocol error " + error);
        });
    };
}

function AssetModel() {
    var self = this;
      
    self.row = ko.observableArray();
    self.currentSymbol = ko.observable();
    self.market = ko.observable(0);
    self.currentExpire = ko.observable();
    self.selectedAsset = ko.observable();
    self.highlight = ko.observable();
   
    var myasset = ({});
    var trade = ({});
    var open = ({});
    var rowLookup = {};
    
     self.putTradeObj = function (tradeObj, openObj){
        trade = tradeObj;
        open = openObj;
    };
  
    self.setDefault = function (message){
        var data = new SomeData(message[0]);
        myasset = data;
        self.currentSymbol(data.symbol);
        self.market(data.price());
        self.currentExpire(data.expire);
        trade.putAsset(data);
        self.highlight(data);
    };
    
   self.loadPositions = function(message) {
     for(var i=0; i<message.length; i++){     
        var data = new SomeData(message[i]);
        self.row.push(data);
        rowLookup[data.symbol] = data;
      }
  };
  
   self.loadAssets = function(data){   
      if (rowLookup[data.symbol].hasOwnProperty("symbol")){ 
            rowLookup[data.symbol].updatePrice(parseFloat(data.price));    
      }
    };

    self.selectedAsset = function(data){ 
        self.currentSymbol(data.symbol);
        self.market(data.price());
        self.currentExpire(data.expire); 
        self.highlight(data);
        trade.putAsset(data);
        open.tradeBox(true);
        open.tradeActive(false);    
        
    }; 
}

function SomeData(some){
    var self = this;
 
    self.symbol = some.symbol;
    self.price = ko.observable(parseFloat(some.price));
    self.payout = '80%';
    self.expire = some.expire;
    
    self.updatePrice = function(newPrice){
        self.price(parseFloat(newPrice));
    };  
  
 }

function TradeModel(stompClient){
    var self = this;
    
    self.isSixty = ko.observable(false);
    self.isTwo = ko.observable(true);
    self.isFive = ko.observable(true);
    self._asset = ko.observable({});
    self._instrument = ko.observable("HighLow");
    self.investment = ko.observable();
    self._time = ko.observable(60);
    self.tradeType = ko.observable();
    self.up = ko.observable(true);
    self.down = ko.observable(true);
    self.targetPrice = ko.observable();
  
  
    self.tradeID = function () {
        return Math.floor(Math.random() * (6725 - 1256)) + 1256;
    };

    var date = new Date();
    
    self.formattedDate = function(){
        var day, month, year, hour, min;
        day = date.getDate();
        month = date.getMonth();
        year = date.getFullYear();
        hour = date.getHours();
        min = date.getMinutes();
        return day + '/' + month  + '/' + year + ' ' + hour + ':' + min;  
    };
    
    
    self.instrument = function(data, event){
        self._instrument(event.currentTarget.id);
    };
    self.time = function(data, event){
        var timer = event.currentTarget.id; 
         if(timer === '60'){
            self.isSixty(false);
            self.isTwo(true);
             self.isFive(true);
        }
        if(timer === '120'){
            self.isSixty(true);
            self.isTwo(false);
             self.isFive(true);
        }
        if(timer === '300'){
            self.isSixty(true);
            self.isTwo(true);
            self.isFive(false);
        }
        self._time(timer);
    }; 
     self.type = function(data, event){
         var _type = event.currentTarget.id;
         if(_type === 'Call'){
             self.up(false);
             self.down(true);
         }if(_type === 'Put'){
              self.up(true);
              self.down(false);
         }
        self.tradeType(_type);
    };
    self.putAsset = function (data){ 
        self._asset(data); 
    };
   
    self.payout = ko.computed(function(){
        var val = 85/100*self.investment();
        return  parseInt(self.investment())+ val;
    });
    
    self.buy = function() {
        
       self.targetPrice(self._asset().price()); 
       var trade = {
           "assets": {"symbol": self._asset().symbol, "price": self._asset().price(), "expire": self._asset().expire},
           "instrument": self._instrument(), 
           "type": self.tradeType(), 
           "amount": self.investment(), 
           "time": self._time(), 
           "bid": self._asset().price()
        };
    
        if(self.tradeType() !== 'Call' & self.tradeType() !=='Put')
            alert('Invalid TradeType Choose High/Low');
        if(self.investment() > balance)
            alert('Not Enough Balance');
        if(isNaN(self.investment()))
            alert('Pls Enter Amount');
        if(self.investment() < 5)
            alert('Enter a Valid Amount, $5 and Above');
        else
            
           stompClient.send("/app/trade", {}, JSON.stringify(trade));
           console.log(trade);
         
    };    
}

function OpenTrade(){
    var self = this;
    
    self.tradeBox = ko.observable(true);
    self.tradeActive = ko.observable(false);
    self.counter = ko.observable(60);
    self.openTrade = ko.observable(false);
    self.noOfTrades = ko.observable(0);
    
   
    self.getCurrentTrade = function (){
         self.tradeActive(true);   
    };
    
    self.showTrade = function(timer){
       self.counter(x(timer, true, false));
       if(timer > 0){
       self.tradeBox(false);
       self.tradeActive(true);
       self.openTrade(true);
       self.noOfTrades(1);
   }else{
       self.tradeBox(true);
       self.tradeActive(false);
       self.openTrade(false);
       self.noOfTrades(0);
    }
      
   self.tradeReturn = function(data){
       alert(data);
   };   
      
   
  function x(T, Z, M){
    f=Math.round;h=T/3600;m=h%1*60;s=m%1*60;
    r=f(h)+'hrs '+f(~~m)+': '+f(s)+'sec';
    Z?r=r.replace(/0\w+/g,''):0;
    M?r=r.replace(/\d+sec/,''):0;
    return r;
  }
   
        
        
      
      
  }; 
  
 
			
			
		
    
    
}












